package com.allwees.bs.task.order.sync;

import cn.hutool.core.collection.CollectionUtil;
import com.allwees.bs.module.lms.service.LogisticsTrackService;
import com.allwees.bs.module.lms.vo.TrackDetailsDto;
import com.allwees.bs.module.oms.dao.OmsOrderItemDao;
import com.allwees.bs.module.oms.service.GeneralOmsOrderItemService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 查询物流订单状态
 */
@Slf4j
@Service

public class OrderSyncLogisticsTask {

    @Autowired
    private LogisticsTrackService logisticsTrackService;

    @Autowired
    private GeneralOmsOrderItemService generalOmsOrderItemService;

    @Resource
    private OmsOrderItemDao omsOrderItemDao;


    @XxlJob(value = "orderSyncLogisticsTask")
    public ReturnT<String> run(String s) {
        doTask();
        return ReturnT.SUCCESS;
    }

    private void doTask() {
        List<String> orderItemUuids = omsOrderItemDao.findShipped();
        if(CollectionUtil.isEmpty(orderItemUuids)){
            return;
        }
        log.info(">>>sync shipped order items,size={}",orderItemUuids.size());
        for (String orderItemUuid : orderItemUuids) {
            try {
                TrackDetailsDto tracking = logisticsTrackService.syncTracking(orderItemUuid);
                if(tracking == null || !tracking.getDelivered()){
                    continue;
                }
                log.info(">>> [OrderSyncLogisticsTask] set OrderItem to delivered,orderItemUuid={}",orderItemUuid);
                generalOmsOrderItemService.doDelivered(orderItemUuid,tracking);
                Thread.sleep(100);
            } catch (Exception e) {
                log.error("error on syncTrack:{}",orderItemUuid, e);
            }
        }
    }
}
